package com.ruoyi.framework.web.service;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.PaWxUser;
import com.ruoyi.system.domain.bo.WxMessageBo;
import com.ruoyi.system.mapper.PaOrderMapper;
import com.ruoyi.system.mapper.PaWxUserMapper;
import com.ruoyi.system.service.IPaWxUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
* @ClassName WxMpLoginService
* @Description 微信公众号发送消息
* @date 2024/8/20 13:45
* @Version 1.0
* @Auther: zhangzhenyu
*/
@Service
@Slf4j
public class WxMpPaService {

    @Autowired
    private  WxMpService wxService;

    @Autowired
    private IPaWxUserService paWxUserService;

    @Autowired
    private TokenService tokenService;

    @Value("${wx.mp.toUserTemplate}")
    private String toUserTemplate;

    @Value("${wx.mp.toSupplierTemplate}")
    private String toSupplierTemplate;


    /**
     * 给供应商发送消息
     * @param wxMessageBo
     * @return
     */
    public R sendSupplierMessage(WxMessageBo wxMessageBo) {
        try {
            //小程序用户id
            String miniAppUserId = wxMessageBo.getToUserId();
            PaWxUser wxMpUser = paWxUserService.selectMpUserByWxUserId(miniAppUserId);
            log.info("查询出公众号用户信息={}", JSONUtil.toJsonStr(wxMpUser));
            if (wxMpUser == null) {
                return R.fail("未找到对应的公众号用户");
            }
            // todo 信息待完善
            String userOpenId = wxMpUser.getOpenId();
            WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
            miniProgram.setAppid("wxd171923b42af1326");
            miniProgram.setPagePath("pages/index");
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .toUser(userOpenId)
                    .templateId(toSupplierTemplate)
                    .miniProgram(miniProgram)
                    .data(Arrays.asList(
                            new WxMpTemplateData("character_string1", "123213213"),
                            new WxMpTemplateData("thing6", "货物名称"),
                            new WxMpTemplateData("character_string12", "3")
                            // ... 其他数据
//                            new WxMpTemplateData("remark", "这是备注信息")
                    ))
                    .build();
            wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {

        }
        return R.ok();
    }

    /**
     * 给用户发送消息
     * @param wxMessageBo
     * @return
     */
    public R sendUserMessage(WxMessageBo wxMessageBo) {
        try {
            //小程序用户id
            String miniAppUserId = wxMessageBo.getToUserId();
            PaWxUser wxMpUser = paWxUserService.selectMpUserByWxUserId(miniAppUserId);
            if (wxMpUser == null) {
                return R.fail("未找到对应的公众号用户");
            }
            String userOpenId = wxMpUser.getOpenId();
            WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
            miniProgram.setAppid("wxd171923b42af1326");
            miniProgram.setPagePath("pages/index");
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .toUser(userOpenId)
                    .templateId(toUserTemplate)
                    .miniProgram(miniProgram)
                    .data(Arrays.asList(
                            new WxMpTemplateData("first", "这是消息的第一部分"),
                            new WxMpTemplateData("keyword1", ""),
                            // ... 其他数据
                            new WxMpTemplateData("remark", "这是备注信息")
                    ))
                    .build();
            wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {

        }
        return R.ok();
    }


    public R sendAdminMessage(WxMessageBo wxMessageBo, HttpServletRequest request) {
        try {
            //httpUtil 封装header
//            String post = HttpUtil.post("https://www.yo-buy.com/admin/wx/mp/sendAdminMessage", JSONUtil.toJsonStr(wxMessageBo));
            HttpResponse response = HttpUtil.createPost("https://www.yo-buy.com/admin/wx/mp/sendAdminMessage")
                    .body(JSONUtil.toJsonStr(wxMessageBo), "application/json;charset=UTF-8")
                    .header("Authorization", tokenService.getToken(request))
                    .execute();
            log.info("发送结果={}", response.body());
        } catch (Exception e) {
            log.info("发送结果失败={}",  e);
            return R.fail("发送失败");
        }
        return R.ok();
    }
}
